package cn.shop.dys.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.shop.dys.R;
import cn.shop.dys.adapter.SearchFailAdapter;
import cn.shop.dys.bean.Product;
import cn.shop.dys.bean.ProductInfo;
import cn.shop.dys.bean.SearchInfo;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.lib_common.CommonUtil;

/**
 * 搜索结果
 * 作者:孙建
 * created at 2016/4/21 10:40
 */
public class SearchResultActivity extends AppCompatActivity implements View.OnClickListener {
    @ViewInject(R.id.iv_common_back)
    private ImageView mBack;
    @ViewInject(R.id.tv_common_index_titile)
    private TextView mTitle;
    @ViewInject(R.id.iv_common_settings)
    private ImageView mSettings;
    @ViewInject(R.id.tv_change_product)
    private TextView mChangeProduct;
    @ViewInject(R.id.gv_recommend_product_list)
    private GridView mRecommendProductList;
    private PopupWindow mPopupWindow;
    private HttpUtils mHttpUtils;
    private Gson mGson;
    private List<ProductInfo> mProducts=new ArrayList<>();
    private boolean isChange=true;
    private SearchFailAdapter mSearchFailAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
        ViewUtils.inject(this);
        mHttpUtils=new HttpUtils();
        mGson=new Gson();
        init();
    }
/**
 * 初始化操作
 * 作者:孙建
 * created at 2016/4/21 19:11
 */
    private void init() {
        initHead();
        initGridView();
    }

    private void initHead() {
        mTitle.setText("搜索结果(0条)");
        mBack.setOnClickListener(this);
        mSettings.setOnClickListener(this);
        mChangeProduct.setOnClickListener(this);
    }

    private void initGridView() {
        initRecommendData(0);
        mRecommendProductList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CommonUtil.showSingleToast(SearchResultActivity.this,"position"+position
                +"mProducts"+mProducts.get(position));
            }
        });
    }
/**
 * 初始化推荐商品关键字
 * 作者:孙建
 * created at 2016/4/21 19:11
 */
    private void initRecommendData(final int startPage) {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST_SEARCH_RECOMMEND, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if(response.equals("searchrecommend")){
                                    String searchKeywords = jsonObject.getString("searchKeywords");
                                    List<String> keywords=mGson.fromJson(searchKeywords,
                                            new TypeToken<List<String>>(){}.getType());
                                    if(keywords==null||keywords.size()==0){
                                        CommonUtil.showToast(SearchResultActivity.this,"推荐商品被偷了");
                                    }else {
                                        for (String keyword : keywords) {
                                            SearchInfo searchInfo = new SearchInfo();
                                            searchInfo.setPage(startPage);
                                            searchInfo.setPageNum(CommonConstant.DEFAULT_PAGE_NUM);
                                            searchInfo.setKeyword(keyword);
                                            initNeedSearchInfo(searchInfo);
                                        }
                                     //   mKeyWords.addAll(keywords);
                                       /* if(isChange){
                                            for (int i = 0; i < keywords.size(); i++) {
                                                SearchInfo searchInfo = new SearchInfo();
                                                searchInfo.setPage(CommonConstant.DEFAULT_PAGE);
                                                searchInfo.setPageNum(CommonConstant.DEFAULT_PAGE_NUM);
                                                searchInfo.setKeyword(keywords.get(i));
                                                initNeedSearchInfo(searchInfo);
                                            }
                                        }else {
                                            for (int i = keywords.size()-1; i >=0 ; i--) {
                                                SearchInfo searchInfo = new SearchInfo();
                                                searchInfo.setPage(CommonConstant.DEFAULT_PAGE);
                                                searchInfo.setPageNum(CommonConstant.DEFAULT_PAGE_NUM);
                                                searchInfo.setKeyword(keywords.get(i));
                                                initNeedSearchInfo(searchInfo);
                                            }
                                        }*/
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(SearchResultActivity.this, "请求失败:错误码为"+statusCode);
                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(SearchResultActivity.this, "网络未连接"+msg);
                    }
                });
    }
    public void setSearchFailAdapter(){
        if(mSearchFailAdapter==null){
            mSearchFailAdapter=new SearchFailAdapter(mProducts,this);
            mRecommendProductList.setAdapter(mSearchFailAdapter);
            mRecommendProductList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int productId = mProducts.get(position).getId();
                    Intent intent=new Intent(SearchResultActivity.this,ProductActivity.class);
                    intent.putExtra("pId",productId);
                    startActivity(intent);
                }
            });

        }else {
            mSearchFailAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化具体推荐商品
     * 作者:孙建
     * created at 2016/4/21 19:12
     */
    private void initNeedSearchInfo(final SearchInfo searchInfo) {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        //http://localhost:8080/market/search?page=0&pageNum=10&orderby=saleDown&keyword=奶粉
        params.addQueryStringParameter("page", searchInfo.getPage()+"");
        params.addQueryStringParameter("pageNum", searchInfo.getPageNum()+"");
        params.addQueryStringParameter("keyword", searchInfo.getKeyword());
        params.addQueryStringParameter("orderby", searchInfo.getOrderby());
        mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST_SEARCH, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if(response.equals("search")){
                                    String productList = jsonObject.getString("productList");
                                    List<ProductInfo> productInfos=mGson.fromJson(productList,new TypeToken<List<ProductInfo>>(){}.getType());
                                    Log.d("test",productInfos.toString());
                                    if(productInfos.size()==0||productInfos==null){
                                        CommonUtil.showToast(SearchResultActivity.this,"推荐商品被偷了");
                                    }else {
                                        mProducts.addAll(productInfos);
                                        if(productInfos.size()>0&&productInfos.size()%CommonConstant.DEFAULT_PAGE_NUM==0){
                                            int myPage=searchInfo.getPage()+1;
                                            SearchInfo searchInfo = new SearchInfo();
                                            searchInfo.setPage(myPage);
                                            searchInfo.setPageNum(CommonConstant.DEFAULT_PAGE_NUM);
                                            searchInfo.setKeyword(searchInfo.getKeyword());
                                            initNeedSearchInfo(searchInfo);
                                        }
                                    }
                                    /*Log.d("test","数量"+mProducts.size());*/
                                    setSearchFailAdapter();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(SearchResultActivity.this, "请求失败:错误码为"+statusCode);
                        }

                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(SearchResultActivity.this, "网络未连接"+msg);
                    }

                });
    }
    /**
     * 事件处理
     * 作者:孙建
     * created at 2016/4/21 19:13
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_common_back:
                finish();
                break;
            case R.id.iv_common_settings:
                initPopupWindow(v);
                break;
            case R.id.tv_change_product:
                setSearchFailAdapter();
               /* isChange=!isChange;
                mProducts.clear();
                initRecommendData(0);*/
                break;
        }
    }
    /**
     * pw处理
     * 作者:孙建
     * created at 2016/4/21 19:13
     */
    private void initPopupWindow (View view){
        View pwView = View.inflate(this, R.layout.view_popupwindow, null);
        View pwTop=pwView.findViewById(R.id.ll_pw_top);
        View pwBottom=pwView.findViewById(R.id.ll_pw_bottom);
        mPopupWindow = new PopupWindow(pwView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mPopupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
        int[] location = new int[2];
        view.getLocationInWindow(location);
        mPopupWindow.showAsDropDown(view, (int) -CommonUtil.dpToPx(this, 100), (int) -CommonUtil.dpToPx(this, 0));
        pwTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SearchResultActivity.this, MessageActivity.class);
                startActivity(intent);
                mPopupWindow.dismiss();
            }
        });
        pwBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SearchResultActivity.this, MainActivity2.class);
                startActivity(intent);
                mPopupWindow.dismiss();
            }
        });
    }
}
